import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
// 引入常量路由
import { constantRoute, asnycRoute, anyRoute } from '@/router/routes'
import router from '@/router'
// 引入深拷贝方法
// @ts-ignore
import cloneDeep from 'lodash/cloneDeep'

// 用于过滤当前用户需要展示的异步路由
function filterAsyncRoute(asnycRoute: any, routes: any) {
    return asnycRoute.filter((item: any) => {
        if (routes.includes(item.name)) {
            if (item.children && item.children.length > 0) {
                item.children = filterAsyncRoute(item.children, routes)
            }
            return true
        }
    })
}

let useUserStore = defineStore('User', {
    state: () => {
        return {
            token: GET_TOKEN(), //存储用户唯一标识符
            menuRoutes: constantRoute,  //仓库存储生成菜单需要数组
            username: '',
            avatar: '',
            buttons: []   //存储当前用户是否包含按钮
        }
    },
    actions: {
        // 用户登录的方法
        async userLogin(data: any) {
            let result = await reqLogin(data)
            if (result.code == 200) {
                this.token = result.data
                SET_TOKEN(result.data)
                return 'ok'
            } else {
                return Promise.reject(new Error(result.data))
            }
        },
        // 获取用户信息
        async userInfo() {
            let result = await reqUserInfo()
            if (result.code == 200) {
                this.username = result.data.name
                this.avatar = result.data.avatar
                this.buttons = result.data.buttons
                // 计算当前用户需要展示的异步路由
                let userAsyncRoute = filterAsyncRoute(cloneDeep(asnycRoute), result.data.routes)
                // 菜单需要的数据整理
                this.menuRoutes = [...constantRoute, ...userAsyncRoute, anyRoute];
                // 动态追加计算完成的异步路由和任意路由
                [...userAsyncRoute, anyRoute].forEach((route: any) => {
                    router.addRoute(route)
                })
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }

        },
        // 退出登录接口
        async userLogout() {
            let result = await reqLogout()
            if (result.code == 200) {
                this.token = ''
                this.username = ''
                this.avatar = ''
                REMOVE_TOKEN()
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        }
    },
    getters: {}
})

export default useUserStore